package com.itmake.sample.repeat.filter;

import cn.hutool.core.text.CharSequenceUtil;
import com.itmake.sample.repeat.wrapper.RepeatRequestWrapper;
import org.springframework.http.MediaType;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 使用过滤器包装请求
 *
 * @author Amjacks
 * @since 2023/08/10
 */
public class RepeatFilter implements Filter {

    /**
     * 使用自定义包装器包装请求
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        ServletRequest requestWrapper = request;
        if (request instanceof HttpServletRequest && CharSequenceUtil.startWithIgnoreCase(request.getContentType(), MediaType.APPLICATION_JSON_VALUE)) {
            requestWrapper = new RepeatRequestWrapper((HttpServletRequest) request, response);
        }
        chain.doFilter(requestWrapper, response);
    }
}
